package service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import db.ConnectDB;
import entity.Card;

//执行插入Card表的服务类
public class CardService {
	
	/**
	 * 
	 * @param card 要办的会员卡的实例
	 * @param memberName 要办会员卡的会员名字
	 * @return void
	 */
	public void addCard(Card card,String memberName){
		//会员名字
		String name = memberName;
		//卡型号
		String cardType = null;
		//卡剩余的使用次数
		int times;
		Connection conn = null;
		//执行sql的Statement
		Statement stmt;
		conn = ConnectDB.getConnection();
		try{
			stmt = conn.createStatement();
			//获得卡型号
			cardType = card.getCardType();
				//SQL结果集
			ResultSet rs ;
			//获得card中所有的记录
			rs = stmt.executeQuery("select * from card;");
			//指针移到最后
			rs.last();
			//确定下一条插入记录的cardId
			int cardId = rs.getRow() + 1;
			//得到所办卡的剩余次数
			times = card.getLastTime();
			
			//如果次数为空即是年卡，否则是次卡
			if(times != 0){
				
				stmt.execute("insert into card (cardId,cardType,lastTimes) values ("+ cardId + "," + '\'' + cardType + '\'' + "," + times +");");
					
			} else {
					
				stmt.execute("insert into card (cardId,cardType) values ("+ cardId + "," + '\'' + cardType + '\'' +");");
					
			}
				
				
			//查询名字为name的会员信息
			rs = null;
			rs = stmt.executeQuery("select * from member where name= \'"+name+"\';");
	
			//获得会员的会员编号
			int memId = 0;
			while(rs.next()){
				memId = rs.getInt(1);
			}
			InformationService infoService = new InformationService();
			infoService.insertIntoMemInfo(stmt, name, memId,cardId, times, cardType);
			//如果times为0，不需要插入剩余使用次数，否则需要插入剩余次数
			/*if(times == 0){
					
				stmt.execute("insert into member_information (cardId,memberId,cardType) values ("+ cardId + "," + memId +","+ "'" + cardType + "'" +");");
				System.out.println("OK. A new " + cardType + " add to " + name + "("+("00"+memId).substring(("00"+memId).length()-3)+").");
					
			} else {
					
				stmt.execute("insert into member_information (cardId,memberId,cardType,lastTimes) values (" + cardId + "," + memId + "," + '\'' + cardType + '\'' + "," + times + ");");
				System.out.println("OK. A new " + cardType + " with " + times + " added to "+name + ".");
				
			}
		*/} catch (SQLException se){
			se.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}
}
